package cn.gemiman.daoyi.module.iot.service.userequipmentplace;

import cn.gemiman.daoyi.framework.common.pojo.PageResult;
import cn.gemiman.daoyi.framework.common.util.object.BeanUtils;
import cn.gemiman.daoyi.module.iot.controller.admin.userequipmentplace.vo.UserEquipmentPlacePageReqVO;
import cn.gemiman.daoyi.module.iot.controller.admin.userequipmentplace.vo.UserEquipmentPlaceSaveReqVO;
import cn.gemiman.daoyi.module.iot.dal.dataobject.userequipment.UserEquipmentDO;
import cn.gemiman.daoyi.module.iot.dal.dataobject.userequipmentplace.UserEquipmentPlaceDO;
import cn.gemiman.daoyi.module.iot.dal.mysql.userequipment.UserEquipmentMapper;
import cn.gemiman.daoyi.module.iot.dal.mysql.userequipmentplace.UserEquipmentPlaceMapper;
import cn.gemiman.daoyi.module.member.api.user.MemberUserApi;
import cn.gemiman.daoyi.module.member.api.user.dto.MemberUserRespDTO;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.List;

import static cn.gemiman.daoyi.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.gemiman.daoyi.module.iot.enums.ErrorCodeConstants.*;
import static cn.gemiman.daoyi.module.member.enums.ErrorCodeConstants.USER_NOT_EXISTS;

/**
 * 会员设备场所 Service 实现类
 *
 * @author 道一源码
 */
@Service
@Validated
public class UserEquipmentPlaceServiceImpl implements UserEquipmentPlaceService {

    @Resource
    private UserEquipmentPlaceMapper userEquipmentPlaceMapper;
    @Resource
    private MemberUserApi memberUserApi;
    @Resource
    private UserEquipmentMapper userEquipmentMapper;

    @Override
    public Long createUserEquipmentPlace(UserEquipmentPlaceSaveReqVO createReqVO) {
        MemberUserRespDTO checkedData = memberUserApi.getUser(createReqVO.getMemberUserId()).getCheckedData();
        if (checkedData == null) {
            throw exception(USER_NOT_EXISTS);
        }
        if (userEquipmentPlaceMapper.exists(Wrappers.lambdaQuery(UserEquipmentPlaceDO.class)
                .eq(UserEquipmentPlaceDO::getMemberUserId, createReqVO.getMemberUserId())
                .eq(UserEquipmentPlaceDO::getEquipmentPlaceName, createReqVO.getEquipmentPlaceName())
        )) {
            throw exception(USER_EQUIPMENT_PLACE_EXISTS);
        }
        // 插入
        UserEquipmentPlaceDO userEquipmentPlace = BeanUtils.toBean(createReqVO, UserEquipmentPlaceDO.class);
        userEquipmentPlaceMapper.insert(userEquipmentPlace);
        // 返回
        return userEquipmentPlace.getId();
    }

    @Override
    public void updateUserEquipmentPlace(UserEquipmentPlaceSaveReqVO updateReqVO) {
        // 校验存在
        UserEquipmentPlaceDO exists = validateUserEquipmentPlaceExists(updateReqVO.getId());
        updateReqVO.setMemberUserId(exists.getMemberUserId());
        if (userEquipmentPlaceMapper.exists(Wrappers.lambdaQuery(UserEquipmentPlaceDO.class)
                .eq(UserEquipmentPlaceDO::getMemberUserId, updateReqVO.getMemberUserId())
                .eq(UserEquipmentPlaceDO::getEquipmentPlaceName, updateReqVO.getEquipmentPlaceName())
                .ne(UserEquipmentPlaceDO::getId, updateReqVO.getId())
        )) {
            throw exception(USER_EQUIPMENT_PLACE_EXISTS);
        }
        // 更新
        UserEquipmentPlaceDO updateObj = BeanUtils.toBean(updateReqVO, UserEquipmentPlaceDO.class);
        userEquipmentPlaceMapper.updateById(updateObj);
    }

    @Override
    public void deleteUserEquipmentPlace(Long id, Long userId) {
        // 校验存在
        UserEquipmentPlaceDO userEquipmentPlaceDO = validateUserEquipmentPlaceExists(id);
        if (!userEquipmentPlaceDO.getMemberUserId().equals(userId)) {
            throw exception(USER_EQUIPMENT_PLACE_NOT_EXISTS);
        }
        if (userEquipmentMapper.exists(Wrappers.lambdaQuery(UserEquipmentDO.class)
                .eq(UserEquipmentDO::getPlaceId, id)
        )) {
            throw exception(USER_EQUIPMENT_PLACE_EXISTS_EQUIPMENT);
        }
        // 删除
        userEquipmentPlaceMapper.deleteById(id);
    }

    @Override
    public void deleteUserEquipmentPlace(Long id) {
        // 校验存在
        validateUserEquipmentPlaceExists(id);
        if (userEquipmentMapper.exists(Wrappers.lambdaQuery(UserEquipmentDO.class)
                .eq(UserEquipmentDO::getPlaceId, id)
        )) {
            throw exception(USER_EQUIPMENT_PLACE_EXISTS_EQUIPMENT);
        }
        // 删除
        userEquipmentPlaceMapper.deleteById(id);
    }

    private UserEquipmentPlaceDO validateUserEquipmentPlaceExists(Long id) {
        UserEquipmentPlaceDO userEquipmentPlaceDO = userEquipmentPlaceMapper.selectById(id);
        if (userEquipmentPlaceDO == null) {
            throw exception(USER_EQUIPMENT_PLACE_NOT_EXISTS);
        }
        return userEquipmentPlaceDO;
    }

    @Override
    public UserEquipmentPlaceDO getUserEquipmentPlace(Long id) {
        UserEquipmentPlaceDO userEquipmentPlaceDO = userEquipmentPlaceMapper.selectById(id);
        MemberUserRespDTO checkedData = memberUserApi.getUser(userEquipmentPlaceDO.getMemberUserId()).getCheckedData();
        userEquipmentPlaceDO.setMemberUser(checkedData);
        return userEquipmentPlaceDO;
    }

    @Override
    public PageResult<UserEquipmentPlaceDO> getUserEquipmentPlacePage(UserEquipmentPlacePageReqVO pageReqVO) {
        PageResult<UserEquipmentPlaceDO> userEquipmentPlaceDOPageResult = userEquipmentPlaceMapper.selectPage(pageReqVO);
        List<UserEquipmentPlaceDO> list = userEquipmentPlaceDOPageResult.getList();
        if (CollUtil.isNotEmpty(list)) {
            List<Long> memberUserIds = list.stream().map(UserEquipmentPlaceDO::getMemberUserId).toList();
            List<MemberUserRespDTO> memberUsers = memberUserApi.getUserList(memberUserIds).getCheckedData();
            list.parallelStream().forEach(uep -> uep.setMemberUser(memberUsers.stream().filter(mu -> mu.getId().equals(uep.getMemberUserId())).findFirst().orElse(null)));
        }
        return userEquipmentPlaceDOPageResult;
    }

}
